<template>
  <div @viewappear="loginAppear" class="container">
    <navbar title="" theme="transparent-light"></navbar>
    <div class="logo-wrapper">
      <image :src="logoSrc" class="logo" resize="cover"></image>
    </div>
    <div class="bottom">
      <div>
        <div v-if="iosShow && !isWEB">
          <div class="register-btn activeable" @click="weixinLogin">
            <text class="register-btn-icon icon register-btn-icon-weixin" >&#xe7e5;</text>
            <text class="register-btn-text"> 微信快捷登录</text>
          </div>
        </div>
        <div class="register-btn activeable phone-login-btn" @click="phoneLogin">
          <text class="register-btn-icon icon" >&#xe7d0;</text>
          <text class="register-btn-text"> 手机号登录</text>
        </div>
        <text class="register-text"  @click="goToRegister">没有账号，现在注册</text>
      </div>
      <div class="btn-container" v-if="false">
        <div class="register-btn activeable phone-login-btn" @click="goToRegister" >

        </div>
        <div class="register-btn activeable phone-login-btn" style="margin-left: 30;" @click="phoneLogin">
          <text class="register-btn-icon icon" >&#xe7d0;</text>
          <text class="register-btn-text"> 手机号登录</text>
        </div>
      </div>
    </div>
    <wxc-loading :show="isLoadingShow"></wxc-loading>
    <wxc-dialog title="登录成功"
                content="您还未绑定微信，通过微信可以实现快捷登录！现在去绑定吗？"
                :show="bindWeixinShow"
                :single="false"
                confirm-text="现在绑定"
                cancel-text="稍后绑定"
                @wxcDialogCancelBtnClicked="cancelWeixinBind"
                @wxcDialogConfirmBtnClicked="doWeixinBind">
    </wxc-dialog>
    <wxc-dialog title="绑定账号"
                content="当前微信还未绑定，您需要绑定账号才能继续登录！"
                :show="bindAccountShow"
                :single="false"
                confirm-text="绑定新账号"
                cancel-text="绑定已有账号"
                @wxcDialogCancelBtnClicked="bindExistsAccount"
                @wxcDialogConfirmBtnClicked="bindNewAccount">
    </wxc-dialog>
    <wxc-dialog title="温馨提示"
                :content="weixinLoginTipContent"
                :show="weixinLoginTipShow"
                :single="false"
                cancel-text="注册账号"
                @wxcDialogCancelBtnClicked="tipDialogCancelBtnClick"
                @wxcDialogConfirmBtnClicked="tipDialogConfirmBtnClick">
    </wxc-dialog>
  </div>
</template>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/icon";
  @import "./sass/buttons";
  @import "./sass/activeable";
  @import "./sass/form";

  .container {
    background-image: linear-gradient(to bottom, $color-primary, $color-primary);
  }

  .bottom {
    justify-content: center;
    height: 700px;
    padding: 0 50px;
    margin-top: 50px;
  }

  .login-bg {
    position: absolute;
    top: 0;
    width: 750px;
    height: 1330px;
  }

  .register-text {
    text-align: center;
    font-size: 32px;
    color: #ffffff;
    margin-top: 30px;
  }

  .register-btn {
    height: 100px;
    text-align: center;
    border-radius: 100px;
    line-height: 100px;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
    margin-bottom: 50px;
    &-text {
      font-size: 34px;
      color: $color;
    }
    &-icon {
      font-size: 50px;
      color: $color;
      &-weixin {
        color: $color-success;
      }
    }
  }

  .logo {
    width: 200px;
    height: 200px;
    border-radius: 30px;
    &-wrapper {
      justify-content: center;
      align-items: center;
      padding-top: 150px;
      opacity: .8;
    }
  }

  .login-form {
    padding: 0 40px;
    margin-top: 60px;
  }

  .login-wrap {
    margin-top: 50px;
  }

  .login-btn {
    flex: 1;
  }

  .phone-login-btn {
    flex: 1;
    background-color: rgba(255, 255, 255, 0.8);
    font-size: 30px;
  }

  .btn-container {
    flex-direction: row;
    justify-content: space-between;
    margin-top: 50px;
  }
</style>
<script>
import {WxcLoading, WxcDialog} from 'weex-ui'
require('./include/page-xdom')
let api = require('./include/api')
let broadcastChannelKeys = require('./include/broadcast-channel-keys')
let BroadcastChannel = require('./include/broadcast-channel')
let loginBroadcastChannel = new BroadcastChannel(broadcastChannelKeys.LOGIN)
let registerBroadcastChannel = new BroadcastChannel(broadcastChannelKeys.REGISTER)
let wexinLoginBroadcaseChannel = new BroadcastChannel(broadcastChannelKeys.WEIXIN_AUTH)
let loginResultBroadcastChannel = new BroadcastChannel(broadcastChannelKeys.LOGIN_RESULT)
let phoneLoginBroadcastChannel = new BroadcastChannel(broadcastChannelKeys.PHONE_LOGIN)
let urlPath = require('./include/url-path')
let navigator = require('./include/xnavigator')
let modal = weex.requireModule('modal')
let weixinApi = weex.requireModule('weixinApi')
let config = require('./include/app-config')
let storageKeys = require('./include/storage-keys')
let storage = require('./include/xstorage')
let login = require('./include/login')
let platform = require('./include/platform')
module.exports = {
  mixins: [],
  components: {
    navbar: require('./components/navbar.vue'),
    xinput: require('./components/input.vue'),
    WxcLoading,
    WxcDialog
  },
  props: {
    phone: {default: ''}
  },
  data () {
    return {
      logoSrc: urlPath.assets('images/logo_mi.png?v=5'),
      hidePwd: true,
      validateOk: false,
      loginDoing: false,
      loginStatus: false,
      weixinLoginListened: false,
      isLoadingShow: false,
      iosShow: false,
      loginBg: urlPath.assets('images/login_bg.jpg?v=3'),
      weixinBinding: false,
      weixinLoginTipShow: false,
      weixinLoginTipContent: '',
      setLocation: false,
      loginData: {},
      bindWeixinShow: false,
      bindAccountShow: false,
      setPhoneBind: false,
      isWEB: platform.isWeb(),
      form: {
        phone: '',
        password: '',
        'remember-me': true
      }
    }
  },
  beforeDestroy () {
    loginBroadcastChannel.postMessage(this.loginStatus)
  },
  created () {
    config.bindConfig(this)
    wexinLoginBroadcaseChannel.onmessage = e => {
      if (e.data.state === 'app_login') {
        // 微信确认登录，现在开始微信登录
        this.weixinLoginHandle(e.data.code)
      } else if (e.data.state === 'app_bind') {
        this.weixinBindHandle(e.data.code)
      }
    }
    loginResultBroadcastChannel.onmessage = e => {
      this.loginData = e.data
      this.handleLoginData(e.data)
    }
    phoneLoginBroadcastChannel.onmessage = e => {
      if (e.data === 'login') {
        navigator.push({
          url: 'phone-login.js'
        })
      }
    }
    registerBroadcastChannel.onmessage = rs => {
      let data = rs.data
      if (data.registered) {
        this.form.phone = data.phone
        this.form.password = data.password
        this.login()
      } else if (data.goRegister) {
        navigator.push('register.js?weixinBindOpenId=' + data.weixinBindOpenId || '')
      }
    }
  },
  methods: {
    toggleHidePwd () {
      this.hidePwd = !this.hidePwd
    },
    validate () {
      if (!this.form.phone || this.form.phone.length !== 11) {
        return false
      }
      if (!this.form.password || this.form.password.length < 6) {
        return false
      }
      return true
    },
    goToRegister () {
      navigator.push('register.js')
    },
    login () {
      if (!this.validate() || this.loginDoing) {
        return
      }
      this.isLoadingShow = true
      this.loginDoing = true
      api.login.password(this.form).done((rs, res) => {
        if (!rs.data.success) {
          modal.alert({message: rs.data.errMsg})
          return
        }
        this.loginData = rs.data
        this.handleLoginData(rs.data, true)
      }).always(rs => {
        this.loginDoing = false
        this.isLoadingShow = false
      })
    },
    loginAppear () {
      if (this.setLocation) {
        storage.getItem('LOCATION_SET_SUCCESS').done(rs => {
          if (rs) {
            this.setLocation = false
            navigator.pop()
          } else {
            navigator.push('my-location.js')
          }
        })
      }
      if (this.setPhoneBind) {
        storage.getItem(storageKeys.PHONE_BIND).done(rs => {
          if (rs) {
            navigator.pop()
          } else {
            this.bindPhone()
          }
        })
      }
    },
    bindPhone () {
      storage.removeItem(storageKeys.PHONE_BIND)
      this.setPhoneBind = true
      navigator.push('bind-phone.js?tip=' + encodeURIComponent('您需要绑定手机号才能继续，请先绑定手机号'))
    },
    handleLoginData (data, registerStatus) {
      this.loginData = data
      if (weex.isRegisteredModule('pushService') && platform.isIOS()) {
        let pushService = weex.requireModule('pushService')
        pushService.bindId(data.userId + '', 'account')
      }
      if (data) {
        if (data.weixinNeitherRegisterNorBind) {
          // 微信没有绑定到账号或者进行过邀请注册
          this.weixinLoginTipContent = '对不起，当前微信还未注册或者绑定，无法进行登录，请先用"微信扫码邀请二维码进行注册"或者"绑定到现有手机账号后"再进行登录！！！'
          this.weixinLoginTipShow = true
        } else {
          login.success(true).done(rs => {
            if (!data.phoneBound) {
              this.bindPhone()
            } else if (!data.weixinBound && !this.isWEB) {
              this.bindWeixinShow = true
            } else {
              navigator.pop()
            }
          })
          this.loginStatus = true

        }
      }
    },
    bindExistsAccount () {
      navigator.push('login-phone.js?weixinBindOpenId=' + this.loginData.weixinBindOpenId)
    },
    bindNewAccount () {
      navigator.push('register.js?weixinBindOpenId=' + this.loginData.weixinBindOpenId)
    },
    cancelWeixinBind () {
      this.bindWeixinShow = false
      navigator.pop()
    },
    doWeixinBind () {
      let weixinApi = weex.requireModule('weixinApi')
      weixinApi.sendAuth({state: 'app_bind'})
      this.bindWeixinShow = false
    },
    weixinLogin () {
      this.bindWeixinShow = false
      weixinApi.sendAuth({state: 'app_login'})
    },
    weixinLoginHandle (code) {
      if (code) {
        this.isLoadingShow = true
        api.login.weixin({
          code: code,
          'remember-me': true
        }).done((rs, res) => {
          this.handleLoginData(rs.data)
        }).always(() => {
          this.isLoadingShow = false
        })
      } else {
        modal.toast({message: '微信授权失败'})
      }
    },
    tipDialogCancelBtnClick () {
      this.weixinLoginTipShow = false
      navigator.push('register.js')
    },
    tipDialogConfirmBtnClick () {
      this.weixinLoginTipShow = false
    },
    weixinBindHandle (code) {
      if (code) {
        this.isLoadingShow = true
        api.user.bindWeixin({weixinAuthCode: code}).done(rs => {
          if (rs.data) {
            modal.toast({message: '微信绑定成功', duration: 0.5})
            this.loginData.weixinBound = true
            this.handleLoginData(this.loginData)
          } else {
            modal.alert({message: '微信已经被其他账号绑定，如需继续绑定，请先对当前微信进行解绑操作，再进行绑定！'})
          }
        }).always(rs => {
          this.isLoadingShow = false
        })
      } else {
        modal.toast({message: '微信授权失败'})
      }
    },
    phoneLogin () {
      navigator.push('login-phone.js')
    }
  }
}
</script>
